package com.shop.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.admin.config.JwtUtils;
import com.shop.admin.mapper.AdminMapper;
import com.shop.admin.model.po.Admins;
import com.shop.admin.model.po.dto.AdminsDto;
import com.shop.admin.service.AdminsService;
import com.shop.ex.ShoppingException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author banxia
 * @since 2023-02-26
 */
@Service
public class AdminsServiceImpl extends ServiceImpl<AdminMapper, Admins> implements AdminsService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public String loginAdmins(String account, String password) {
        LambdaQueryWrapper<Admins> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Admins::getAccount,account);
        Admins admins = adminMapper.selectOne(wrapper);
        //这里暂时不对密码进行加密
        boolean tag = admins.getPassword().equals(password);
        if (!tag){
            ShoppingException.ThrowShoppingException("admin密码错误");
        }
        String json = JSONObject.toJSONString(admins);
        String token = JwtUtils.getJwtToken(json);
        return token;
    }

    @Override
    public void addAdmins(AdminsDto adminsDto) {
        Admins admins = new Admins();
        BeanUtils.copyProperties(adminsDto,admins);
        int i = adminMapper.insert(admins);
        if (i == 0) {
            ShoppingException.ThrowShoppingException("添加失败");
        }
    }

    @Override
    public void updateAdmins(AdminsDto adminsDto, Long id) {
        Admins admins=new Admins();
        BeanUtils.copyProperties(adminsDto,admins);
        admins.setId(id);
        int i = adminMapper.updateById(admins);
        if (i == 0) {
            ShoppingException.ThrowShoppingException("更新失败");
        }
    }

    @Override
    public void removeAdmins(Long id) {
        int i = adminMapper.deleteById(id);
        if (i == 0) {
            ShoppingException.ThrowShoppingException("删除失败");
        }
    }

    @Override
    public List<Admins> selectAdmins() {
        List<Admins> admins = adminMapper.selectList(null);
        return admins;
    }
}
